import random
import time

from ascript.android.node import Selector
from ascript.android import action
import re
from .utils import timeSleep, closeAdvertisingOnce, slide,heightPixels,clickGuangGao

# 滚动元素
def elementVisible():
    print('进入滚动获取元素')
    while True:
        element = Selector().path("/FrameLayout/FrameLayout/LynxFlattenUI").find_all()
        if element == None:
            continue
        print('元素个数',len(element))
        # 点击广告
        clickGuangGao()
        # 关闭广告
        closeAdvertisingOnce()
        for itm in element:
            if ('立即领取' in itm.text or '去领取' in itm.text) and itm.path == '/FrameLayout/FrameLayout/LynxFlattenUI' and itm.visible==True and itm.center_y<int(heightPixels/2):
                print('元素成功显示',itm)
                return itm
        slide(num=105)
        timeSleep()

# 吃饭补贴
def eatBuTie():
    while True:
        element = Selector().path("/FrameLayout/FrameLayout/LynxFlattenUI").find_all()
        timeSleep()
        if element:
            break
    for itm in element:
        center_x = itm.center_x
        center_y = itm.center_y
        if ('立即领取' in itm.text or '去领取' in itm.text) and itm.path == '/FrameLayout/FrameLayout/LynxFlattenUI':
            # 判断元素是否在可见区域
            if itm.visible==False:
                # 不在可见区域则滑动到可见区域
                visible = elementVisible()
                center_x = visible.center_x
                center_y = visible.center_y
            # 点击补贴
            print('点击吃饭补贴')
            timeSleep()
            action.click(x=center_x, y=center_y, dur=random.randint(20, 500))
            for itm in range(10):
                for i in range(5):
                    # 等待时间
                    timeSleep()
                    # 点击广告
                    print('吃饭补贴=================点击广告' + str(itm))
                    clickGuangGao()
                    # 关闭广告
                    print('吃饭补贴=================点击关闭广告')
                    closeAdvertisingOnce()
                    timeSleep()
                    fuli = Selector().id("com.phoenix.read:id/acv").find()
                    if fuli:
                        print('退出返回主页')
                        return
